//
//  HttpRequest.m
//  Dear
//
//  Created by 陈俊俊 on 15/7/11.
//  Copyright (c) 2015年 陈俊俊. All rights reserved.
//

#import "HttpRequest.h"


#import "DearLoadingView.h"
#import "Reachability.h"
#define MAX_CONCURRENCY_UPLOAD      1
#define MAX_CONCURRENCY_DOWNLOAD    3

#define ERROR_PARAMETER             @"Error Parameter(s)"

NSString * const DearErrorDomain = @"DearErrorDomain";

@interface HttpRequest ()
/**
 *  The upload operation queue on which upload request operations are scheduled and run.
 */
@property (nonatomic, strong) NSOperationQueue *uploadOperationQueue;

/**
 *  The download operation queue on which download request operations are scheduled and run.
 */
@property (nonatomic, strong) NSOperationQueue *downloadOperationQueue;


@end

@implementation HttpRequest

#pragma mark - Class Method

+ (instancetype)sharedInstance {
    static HttpRequest *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });
    
    return _sharedInstance;
}

+ (NSError *)ErrorWithMsg:(NSString *)nsErrorMsg code:(NSInteger)uiCode {
    NSDictionary *userInfo =
    nsErrorMsg ? @{ NSLocalizedFailureReasonErrorKey : nsErrorMsg } : nil;
    
    NSError *error =
    [[NSError alloc] initWithDomain:DearErrorDomain
                               code:uiCode userInfo:userInfo];
    
    return error;
}

+ (id)GetErrorMsgFromOperation:(AFHTTPRequestOperation *)operation error:(NSError *)error
{
    id data = operation.responseObject;
    if ([data isKindOfClass:[NSDictionary class]]) {
        NSString *errorMsg = data[ @"message" ];
        return [[self class] ErrorWithMsg:errorMsg code:[[operation response] statusCode]];
    }
    else {
        return error;
    }
}


#pragma mark - Life Cycle
- (id)init {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
    
    self.uploadOperationQueue = [[NSOperationQueue alloc] init];
    [self.uploadOperationQueue setMaxConcurrentOperationCount:MAX_CONCURRENCY_UPLOAD];
    
    self.downloadOperationQueue = [[NSOperationQueue alloc] init];
    [self.downloadOperationQueue setMaxConcurrentOperationCount:MAX_CONCURRENCY_DOWNLOAD];
    
    return self;
}

- (void)POST:(NSString *)urlStr
  parameters:(id)parameters
     success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))succ
     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))fail
{
    if (![self isHasNetWork]) {
        [DearLoadingView showTips:@"无网络连接，请检查当前网络环境"];
        return;
    }
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        succ(operation, responseObject);
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        fail(operation, [[self class] GetErrorMsgFromOperation:operation error:error]);
    };
    [DearLoadingView showProgressLabel:@"正在加载中..."];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/html",@"text/plain",nil];
    
    [manager POST:urlStr
       parameters:parameters
          success:success
          failure:failure];
}

- (void)uploadPOST:(NSString *)urlStr
  parameters:(id)parameters
     success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))succ
     failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))fail
{
    void (^success)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
        succ(operation, responseObject);
    };
    
    void (^failure)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
        fail(operation, [[self class] GetErrorMsgFromOperation:operation error:error]);
    };
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/html",nil];
    
    [manager POST:urlStr
       parameters:parameters
          success:success
          failure:failure];
}
#pragma mark - 检查是否有网络连接
- (BOOL)isHasNetWork{
    Reachability *reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    BOOL isHaveNet = [reachability isReachable];
    return isHaveNet;
}


@end
